package com.medical.assistant.service;

import com.alibaba.dashscope.app.Application;
import com.alibaba.dashscope.app.ApplicationParam;
import com.alibaba.dashscope.app.ApplicationResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import io.reactivex.Flowable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Schedulers;

@Service
public class AliLLMService {
    @Value("${ali.llm.apikey}")
    private String apiKey;

    @Value("${ali.llm.appid}")
    private String appId;

    public Flux<Object> askLLMStream(String prompt) {
        return Flux.create(sink -> {
            try {
                ApplicationParam param = ApplicationParam.builder()
                        .apiKey(apiKey)
                        .appId(appId)
                        .prompt(prompt)
                        .incrementalOutput(true)  // 增量输出模式
                        .build();
                Application application = new Application();
                Flowable<ApplicationResult> result = application.streamCall(param);

                // 用于跟踪已发送的内容（处理累积输出的情况）
                final StringBuilder previousContent = new StringBuilder();
                final int[] chunkCount = {0};

                // 使用非阻塞的 subscribe 实现真正的流式输出
                result.subscribe(
                    data -> {
                        chunkCount[0]++;
                        String fullText = data.getOutput().getText();
                        
                        if (fullText != null && !fullText.isEmpty()) {
                            // 检查是否为增量输出还是累积输出
                            String incrementalText;
                            if (fullText.startsWith(previousContent.toString())) {
                                // 累积输出：只取新增部分
                                incrementalText = fullText.substring(previousContent.length());
                                previousContent.setLength(0);
                                previousContent.append(fullText);
                                System.out.println("📦 [" + chunkCount[0] + "] 累积模式，增量部分 (" + incrementalText.length() + " 字符): " + incrementalText);
                            } else {
                                // 增量输出：直接使用
                                incrementalText = fullText;
                                previousContent.append(fullText);
                                System.out.println("📦 [" + chunkCount[0] + "] 增量模式 (" + incrementalText.length() + " 字符): " + incrementalText);
                            }
                            
                            if (!incrementalText.isEmpty()) {
                                sink.next(incrementalText);
                                System.out.println("✅ [" + chunkCount[0] + "] 已发送到前端 | 时间: " + System.currentTimeMillis());
                            }
                        }
                    },
                    error -> {
                        // onError: 处理错误
                        System.err.println("❌ 流式输出错误: " + error.getMessage());
                        sink.error(error);
                    },
                    () -> {
                        // onComplete: 流完成
                        System.out.println("🏁 流式输出完成，共 " + chunkCount[0] + " 个数据块 | 时间: " + System.currentTimeMillis());
                        sink.complete();
                    }
                );

            } catch (ApiException | NoApiKeyException | InputRequiredException e) {
                sink.error(e);
            } catch (Exception e) {
                sink.error(e);
            }
        }).subscribeOn(Schedulers.boundedElastic());
    }
}